﻿'use client'

import { useState } from 'react'
import { Calculator, RotateCcw, ArrowRightLeft } from 'lucide-react'

const conversionRates = {
  length: {
    meter: 1,
    kilometer: 0.001,
    centimeter: 100,
    millimeter: 1000,
    inch: 39.3701,
    foot: 3.28084,
    yard: 1.09361,
    mile: 0.000621371
  },
  weight: {
    kilogram: 1,
    gram: 1000,
    pound: 2.20462,
    ounce: 35.274,
    ton: 0.001,
    stone: 0.157473
  },
  temperature: {
    celsius: (c: number) => ({ celsius: c, fahrenheit: c * 9/5 + 32, kelvin: c + 273.15 }),
    fahrenheit: (f: number) => ({ celsius: (f - 32) * 5/9, fahrenheit: f, kelvin: (f - 32) * 5/9 + 273.15 }),
    kelvin: (k: number) => ({ celsius: k - 273.15, fahrenheit: (k - 273.15) * 9/5 + 32, kelvin: k })
  },
  area: {
    'square-meter': 1,
    'square-kilometer': 0.000001,
    'square-centimeter': 10000,
    'square-inch': 1550.0031,
    'square-foot': 10.7639,
    acre: 0.000247105,
    hectare: 0.0001
  },
  volume: {
    liter: 1,
    milliliter: 1000,
    'cubic-meter': 0.001,
    gallon: 0.264172,
    quart: 1.05669,
    pint: 2.11338,
    cup: 4.22675,
    'fluid-ounce': 33.814
  }
}

const unitLabels = {
  length: {
    meter: '米 (m)',
    kilometer: '千米 (km)',
    centimeter: '厘米 (cm)',
    millimeter: '毫米 (mm)',
    inch: '英寸 (in)',
    foot: '英尺 (ft)',
    yard: '码 (yd)',
    mile: '英里 (mi)'
  },
  weight: {
    kilogram: '千克 (kg)',
    gram: '克 (g)',
    pound: '磅 (lb)',
    ounce: '盎司 (oz)',
    ton: '吨 (t)',
    stone: '英石 (st)'
  },
  temperature: {
    celsius: '摄氏度 (°C)',
    fahrenheit: '华氏度 (°F)',
    kelvin: '开尔文 (K)'
  },
  area: {
    'square-meter': '平方米 (m²)',
    'square-kilometer': '平方千米 (km²)',
    'square-centimeter': '平方厘米 (cm²)',
    'square-inch': '平方英寸 (in²)',
    'square-foot': '平方英尺 (ft²)',
    acre: '英亩 (acre)',
    hectare: '公顷 (ha)'
  },
  volume: {
    liter: '升 (L)',
    milliliter: '毫升 (mL)',
    'cubic-meter': '立方米 (m³)',
    gallon: '加仑 (gal)',
    quart: '夸脱 (qt)',
    pint: '品脱 (pt)',
    cup: '杯 (cup)',
    'fluid-ounce': '液体盎司 (fl oz)'
  }
}

export default function UnitConverterPage() {
  const [category, setCategory] = useState('length')
  const [fromUnit, setFromUnit] = useState('meter')
  const [toUnit, setToUnit] = useState('kilometer')
  const [inputValue, setInputValue] = useState('')
  const [result, setResult] = useState('')

  const convertUnits = (value: string) => {
    const numValue = parseFloat(value)
    if (isNaN(numValue)) {
      setResult('')
      return
    }

    if (category === 'temperature') {
      const tempRates = conversionRates.temperature as any
      const converted = tempRates[fromUnit](numValue)
      setResult(converted[toUnit].toFixed(6))
    } else {
      const rates = conversionRates[category as keyof typeof conversionRates] as any
      const baseValue = numValue / rates[fromUnit]
      const convertedValue = baseValue * rates[toUnit]
      setResult(convertedValue.toFixed(6))
    }
  }

  const handleInputChange = (value: string) => {
    setInputValue(value)
    convertUnits(value)
  }

  const handleCategoryChange = (newCategory: string) => {
    setCategory(newCategory)
    const units = Object.keys(conversionRates[newCategory as keyof typeof conversionRates])
    setFromUnit(units[0])
    setToUnit(units[1] || units[0])
    setInputValue('')
    setResult('')
  }

  const swapUnits = () => {
    const temp = fromUnit
    setFromUnit(toUnit)
    setToUnit(temp)
    if (inputValue) {
      convertUnits(inputValue)
    }
  }

  const currentUnits = Object.keys(conversionRates[category as keyof typeof conversionRates])
  const currentLabels = unitLabels[category as keyof typeof unitLabels]

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">单位转换工具</h1>
          <p className="text-gray-600">支持长度、重量、温度、面积、体积等多种单位转换</p>
        </div>

        <div className="mb-6 flex gap-4">
          <button
            onClick={() => convertUnits(inputValue)}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2"
          >
            <Calculator className="w-4 h-4" />
            转换
          </button>
          <button
            onClick={swapUnits}
            className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 flex items-center gap-2"
          >
            <ArrowRightLeft className="w-4 h-4" />
            交换单位
          </button>
          <button
            onClick={() => { setInputValue(''); setResult('') }}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-2"
          >
            <RotateCcw className="w-4 h-4" />
            清空
          </button>
        </div>

        <div className="mb-6">
          <label className="block text-sm font-medium text-gray-700 mb-2">转换类别</label>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
            {Object.keys(conversionRates).map((cat) => (
              <button
                key={cat}
                onClick={() => handleCategoryChange(cat)}
                className={p-2 text-sm rounded-lg border }
              >
                {cat === 'length' && '长度'}
                {cat === 'weight' && '重量'}
                {cat === 'temperature' && '温度'}
                {cat === 'area' && '面积'}
                {cat === 'volume' && '体积'}
              </button>
            ))}
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">从</label>
              <select
                value={fromUnit}
                onChange={(e) => {
                  setFromUnit(e.target.value)
                  if (inputValue) {
                    convertUnits(inputValue)
                  }
                }}
                className="w-full p-2 border border-gray-300 rounded-md"
              >
                {currentUnits.map((unit) => (
                  <option key={unit} value={unit}>
                    {currentLabels[unit as keyof typeof currentLabels]}
                  </option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">输入数值</label>
              <input
                type="number"
                value={inputValue}
                onChange={(e) => handleInputChange(e.target.value)}
                placeholder="输入要转换的数值..."
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </div>

          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">到</label>
              <select
                value={toUnit}
                onChange={(e) => {
                  setToUnit(e.target.value)
                  if (inputValue) {
                    convertUnits(inputValue)
                  }
                }}
                className="w-full p-2 border border-gray-300 rounded-md"
              >
                {currentUnits.map((unit) => (
                  <option key={unit} value={unit}>
                    {currentLabels[unit as keyof typeof currentLabels]}
                  </option>
                ))}
              </select>
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">转换结果</label>
              <input
                type="text"
                value={result}
                readOnly
                placeholder="转换结果将在这里显示..."
                className="w-full p-3 border border-gray-300 rounded-lg bg-gray-50"
              />
            </div>
          </div>
        </div>

        <div className="mt-8 bg-gray-50 p-4 rounded-lg">
          <h4 className="font-medium text-gray-900 mb-2">常用转换示例</h4>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <button
              onClick={() => {
                setCategory('length')
                setFromUnit('meter')
                setToUnit('foot')
                handleInputChange('1')
              }}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">长度转换</div>
              <div className="text-xs text-gray-500 mt-1">1米 = 3.28英尺</div>
            </button>
            <button
              onClick={() => {
                setCategory('weight')
                setFromUnit('kilogram')
                setToUnit('pound')
                handleInputChange('1')
              }}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">重量转换</div>
              <div className="text-xs text-gray-500 mt-1">1千克 = 2.20磅</div>
            </button>
            <button
              onClick={() => {
                setCategory('temperature')
                setFromUnit('celsius')
                setToUnit('fahrenheit')
                handleInputChange('0')
              }}
              className="text-left p-3 bg-white rounded border hover:bg-gray-50"
            >
              <div className="font-medium text-sm">温度转换</div>
              <div className="text-xs text-gray-500 mt-1">0°C = 32°F</div>
            </button>
          </div>
        </div>

        <div className="mt-6 bg-blue-50 p-4 rounded-lg">
          <h4 className="font-medium text-blue-900 mb-2">支持的转换类别</h4>
          <ul className="text-blue-800 text-sm space-y-1">
            <li>• <strong>长度:</strong> 米、千米、厘米、毫米、英寸、英尺、码、英里</li>
            <li>• <strong>重量:</strong> 千克、克、磅、盎司、吨、英石</li>
            <li>• <strong>温度:</strong> 摄氏度、华氏度、开尔文</li>
            <li>• <strong>面积:</strong> 平方米、平方千米、平方厘米、平方英寸、平方英尺、英亩、公顷</li>
            <li>• <strong>体积:</strong> 升、毫升、立方米、加仑、夸脱、品脱、杯、液体盎司</li>
          </ul>
        </div>
      </div>
    </div>
  )
}
